package com.chinacoal.microservice.impl.service.impl;

import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;

import org.apache.commons.lang3.StringUtils;
import org.dom4j.Document;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.HttpMethod;
import org.springframework.stereotype.Service;

import com.chinacoal.microservice.api.model.ForeignTaskParam;
import com.chinacoal.microservice.api.model.resource.BusinessData;
import com.chinacoal.microservice.api.model.resource.DictionaryCanvasData;
import com.chinacoal.microservice.api.model.resource.FormCanvasData;
import com.chinacoal.microservice.api.model.resource.NewPageCanvasData;
import com.chinacoal.microservice.api.model.resource.RecordData;
import com.chinacoal.microservice.api.model.resource.TableCanvasData;
import com.chinacoal.microservice.impl.service.PurchaseTaskService;
import com.chinacoal.microservice.impl.service.UtaskInfoService;
import com.chinacoal.microservice.util.result.CodeMsg;
import com.chinacoal.microservice.util.result.Result;
import com.chinacoal.microservice.util.tool.Tool;

/**
 * 
 * 描述 : 采购电商ServiceImpl
 * 创建人 : yn
 * 创建时间 : 2020年5月20日 下午2:27:58
 * 版本 : 1.0
 * 包名 : com.chinacoal.microservice.impl.service.impl
 * 类名 : PurchaseTaskServiceImpl
 */
@Service
public class PurchaseTaskServiceImpl implements PurchaseTaskService {
	
	/**
	 * logger日志
	 */
	private Logger logger = LoggerFactory.getLogger(getClass());

	/**
	 * 代办Service
	 */
	@Resource
	private UtaskInfoService utaskInfoService;
	
    /**
     * 采购电商待办地址
     */
    @Value("${ccecTask.wsdl}")
    private String ccecTaskPath;
	
    /**
     * 
     * 创建人 : yn
     * 创建时间 : 2020年5月20日 下午2:52:55
     * 描述 : 采购电商系统待办详情
     * 包名 : com.chinacoal.microservice.impl.service.impl
     * 方法名 : getDetails
     *  Result<BusinessData>  
     *  @throws
     */
	@Override
	public Result<BusinessData> getDetails(ForeignTaskParam foreignTaskParam) throws Exception {
		BusinessData businessData = new BusinessData(); // 创建采购电商XML数据转换对象类
//		UtaskInfoEntity utaskInfoEntity = utaskInfoService.getTask(foreignTaskParam.getSysCode(),foreignTaskParam.getBusinessId());
//		if (utaskInfoEntity == null) {
//			return Result.error(CodeMsg.BIND_ERROR.fillArgs("获取代办详情失败,请确认！"));
//		}
		try {
//			String[] sysTaskIdArray = utaskInfoEntity.getSysTaskId().split("-"); // 拆分待办ID(2020051627(单据编码)-58000592-11(应用类型))
			String[] sysTaskIdArray = foreignTaskParam.getSysTaskId().split("-"); // 拆分待办ID(2020051627(单据编码)-58000592-11(应用类型))
			String appType = sysTaskIdArray[2]; // 应用类型：1--采购方案审核；2--采购方案变更审批；7--定标报告审批；11--询价结果审批；
			String workitemId = sysTaskIdArray[0]; // 单据编码
			
			String paramXml = "";
			paramXml += "<soapenv:Envelope xmlns:soapenv=\"http://schemas.xmlsoap.org/soap/envelope/\" xmlns:ccec=\"http://ccec\">";
			paramXml += "<soapenv:Header/>";
			paramXml += 	"<soapenv:Body>";
			paramXml += 		"<ccec:getToDoJobDetail>";
			paramXml +=				"<ccec:clientCode>pecid</ccec:clientCode>";
			paramXml +=				"<ccec:appType>" + appType + "</ccec:appType>";
			paramXml +=				"<ccec:workitemid>" + workitemId + "</ccec:workitemid>";
			paramXml += 		"</ccec:getToDoJobDetail>";
			paramXml +=		"</soapenv:Body>";
			paramXml += "</soapenv:Envelope>";
			
			Map<String, String> headParam = new HashMap<String, String>();
			headParam.put("SOAPAction", "");
			headParam.put("Content-Type", "text/xml;charset=UTF-8");
			
			String soapXml = Tool.invokeInterfaceWebService(ccecTaskPath, paramXml, headParam, HttpMethod.POST);
			if (StringUtils.isNoneBlank(soapXml)) { // 判断SoapXml是否为空
				String resultXml = analysisSoapXml(soapXml, "getToDoJobDetailReturn");
				if (StringUtils.isNoneBlank(resultXml)) {
					Document doc = DocumentHelper.parseText(resultXml);
					Element rootE = doc.getRootElement();
					
					// 基础信息
					if (rootE.element("pecInfo").element("baseInfo") != null) {
						FormCanvasData baseInfoFormData = new FormCanvasData();
						Element baseInfoE = rootE.element("pecInfo").element("baseInfo");
						for (Iterator<Element> baseInfoIterable = baseInfoE.elementIterator(); baseInfoIterable.hasNext();) {
							Element baseInfoNodeE = baseInfoIterable.next();
							baseInfoFormData.add(baseInfoNodeE.attributeValue("name"), baseInfoNodeE.attributeValue("value"));
						}
						baseInfoFormData.setName("基本信息");
						businessData.addFormCanvasData(baseInfoFormData);
					}
					
					// 应用类型：1--采购方案审核；2--采购方案变更审批；
					if ("1".equals(appType) || "2".equals(appType)) {
						// 采购包明细
						if (rootE.element("pecInfo").element("baoInfo") != null) {
							Element baoInfoE = rootE.element("pecInfo").element("baoInfo");
							for (Iterator<Element> baoInfoIterable = baoInfoE.elementIterator(); baoInfoIterable.hasNext();) {
								Element baoInfoNoneE = baoInfoIterable.next();
								TableCanvasData tableCanvasData = new TableCanvasData();
								
								// 采购包明细
								if (baoInfoNoneE.element("baoBaseInfo") != null) {
									Element baoBaseInfoE = baoInfoNoneE.element("baoBaseInfo");
									for (Iterator<Element> baoBaseInfoIterable = baoBaseInfoE.elementIterator(); baoBaseInfoIterable.hasNext();) {
										Element baoBaseItemNodeE = baoBaseInfoIterable.next();
										tableCanvasData.add(new RecordData().add(baoBaseItemNodeE.attributeValue("id"),
												baoBaseItemNodeE.attributeValue("name"), baoBaseItemNodeE.attributeValue("value")));
									}
									tableCanvasData.setName("采购包明细");
									tableCanvasData.add(new RecordData().add("newPage",
											"1".equals(appType) ? "采购包编码-物资项数超链,采购包编码-供应商数超链,查看采购计划详情超链"
													: "采购包编码-物资项数超链,采购包编码-供应商数超链",
											"1".equals(appType) ? "采购包编码-物资项数超链,采购包编码-供应商数超链,查看采购计划详情超链"
													: "采购包编码-物资项数超链,采购包编码-供应商数超链"));
									businessData.addTableCanvasData(tableCanvasData);
									
									// 采购包编码超链信息---物资
									tableCanvasData = new TableCanvasData();
									NewPageCanvasData newPageCanvasData = new NewPageCanvasData();
									if (baoInfoNoneE.element("wzInfo") != null) {
										Element wzInfoE = baoInfoNoneE.element("wzInfo");
										for (Iterator<Element> wzInfoIterable = wzInfoE.elementIterator(); wzInfoIterable.hasNext();) {
											Element wzInfoNodeE = wzInfoIterable.next();
											RecordData recordData = new RecordData();
											for(Iterator<Element> wzItemIterable = wzInfoNodeE.elementIterator(); wzItemIterable.hasNext();) {
												Element wzItemNoneE = wzItemIterable.next();
												recordData.add(wzItemNoneE.attributeValue("id"), wzItemNoneE.attributeValue("name"), wzItemNoneE.attributeValue("value"));
											}
											tableCanvasData.add(recordData);
										}
										newPageCanvasData.addTableCanvasData(tableCanvasData);
										newPageCanvasData.setNewPageType("newPage");
										newPageCanvasData.setName("采购包编码-物资项数超链");
										businessData.addNewPageCanvasData(newPageCanvasData);
									}
									
									// 采购包编码超链信息---供应商
									tableCanvasData = new TableCanvasData();
									newPageCanvasData = new NewPageCanvasData();
									if (baoInfoNoneE.element("gysInfo") != null) {
										Element gysInfoE = baoInfoNoneE.element("gysInfo");
										for (Iterator<Element> gysInfoIterable = gysInfoE.elementIterator(); gysInfoIterable.hasNext();) {
											Element gysInfoNodeE = gysInfoIterable.next();
											RecordData recordData = new RecordData();
											for(Iterator<Element> gysItemIterable = gysInfoNodeE.elementIterator(); gysItemIterable.hasNext();) {
												Element gysItemNoneE = gysItemIterable.next();
												recordData.add(gysItemNoneE.attributeValue("id"), gysItemNoneE.attributeValue("name"), gysItemNoneE.attributeValue("value"));
											}
											tableCanvasData.add(recordData);
										}
										newPageCanvasData.addTableCanvasData(tableCanvasData);
										newPageCanvasData.setNewPageType("newPage");
										newPageCanvasData.setName("采购包编码-供应商数超链");
										businessData.addNewPageCanvasData(newPageCanvasData);
									}
									
									// 查看采购计划详情超链
									if ("1".equals(appType)) {
										newPageCanvasData = new NewPageCanvasData();
										if (baoInfoNoneE.element("jhMxInfo") != null) {
											Element jhMxInfoE = baoInfoNoneE.element("jhMxInfo");
											tableCanvasData = new TableCanvasData();
											for (Iterator<Element> iterableJhMx = jhMxInfoE.elementIterator(); iterableJhMx.hasNext();) {
												Element nodeElementJhMx = iterableJhMx.next();
												RecordData recordData = new RecordData();
												for(Iterator<Element> jhMxItemIterable = nodeElementJhMx.elementIterator(); jhMxItemIterable.hasNext();) {
													Element jhMxItemNoneE = jhMxItemIterable.next();
													recordData.add(jhMxItemNoneE.attributeValue("id"), jhMxItemNoneE.attributeValue("name"), jhMxItemNoneE.attributeValue("value"));
												}
												tableCanvasData.add(recordData);
											}
											newPageCanvasData.addTableCanvasData(tableCanvasData);
											newPageCanvasData.setNewPageType("newPage");
											newPageCanvasData.setName("查看采购计划详情超链");
											businessData.addNewPageCanvasData(newPageCanvasData);
										}
									}
								}
							}
						}
					}
					
					// 应用类型：7--定标报告审批；11--询价结果审批；
					if ("7".equals(appType) || "11".equals(appType)) {
						// 供应商明细
						if (rootE.element("pecInfo").element("gysInfo") != null) {
							TableCanvasData tableCanvasData = new TableCanvasData();
							Element gysInfoE = rootE.element("pecInfo").element("gysInfo");
							for (Iterator<Element> gysInfoIterable = gysInfoE.elementIterator(); gysInfoIterable.hasNext();) {
								Element gysInfoNoneE = gysInfoIterable.next();
								RecordData recordData = new RecordData();
								for (Iterator<Element> gysItemIterable = gysInfoNoneE.elementIterator(); gysItemIterable.hasNext();) {
									Element gysItemNodeE = gysItemIterable.next();
									recordData.add(gysItemNodeE.attributeValue("id"), gysItemNodeE.attributeValue("name"),
											gysItemNodeE.attributeValue("value"));
								}
								tableCanvasData.add(recordData);
							}
							tableCanvasData.setName("供应商明细");
							businessData.addTableCanvasData(tableCanvasData);
						}
					}
					
					// 审批信息
					if (rootE.element("pecInfo").element("adviseInfo") != null) {
						TableCanvasData approvalRecords = new TableCanvasData();
						Element adviseInfoE = rootE.element("pecInfo").element("adviseInfo");
						for (Iterator<Element> adviseInfoIterable = adviseInfoE.elementIterator(); adviseInfoIterable.hasNext();) {
							Element adviseE = adviseInfoIterable.next();
							RecordData recordData = new RecordData();
							for (Iterator<Element> adviseIterable = adviseE.elementIterator(); adviseIterable.hasNext();) {
								Element adviseNodeE = adviseIterable.next();
								/** <advise> 
							        <element value="11" name="序号" id="rn"/>  
							        <element value="王璇" name="审核人" loginname="58000592" id="approvername"/>  
							        <element value="中煤信息技术（北京）有限公司" name="审核单位" id="approvedeptname"/>  
							        <element value="2020-04-17 20:45:21" name="审核时间" id="approvedate"/>  
							        <element value="\u540c\u610f" name="审核意见" id="comments"/> 
							      </advise> **/
								String name = adviseNodeE.attributeValue("name");
								String value = adviseNodeE.attributeValue("value");
								String id = "";
								if (StringUtils.isNoneBlank(name)) {
									switch (name) {
										case "序号":
											id = "number";
										break;
										case "审核人":
											id = "handler";
											break;
										case "审核单位":
											id = "handlerDeptName";
											break;
										case "审核时间":
											id = "handlerDate";
											break;
										case "审核意见":
											id = "opinion";
											if (StringUtils.isNoneBlank(value)) {
												value = unicode(value);
											}
											break;
										
										default:
											break;
										}
								}
								recordData.add(id, name, value);
							}
							approvalRecords.add(recordData);
						}
						approvalRecords.setName("审批信息");
						businessData.setApprovalRecords(approvalRecords);
					}
					
					// 附件信息
					if (rootE.element("pecInfo").element("attachementInfo") != null) {
						TableCanvasData fileInfo = new TableCanvasData();
						Element fileInfoE = rootE.element("pecInfo").element("attachementInfo");
						for (Iterator<Element> fileInfoIterable = fileInfoE.elementIterator(); fileInfoIterable.hasNext();) {
							Element nodeE = fileInfoIterable.next();
							RecordData recordData = new RecordData();
							/**
							 * <element value="" url=
							 * "http://172.16.0.240:7002/uploadMoreFile.do?actionType=downLoadBlob&amp;fjmc=开发公司定标会议纪要.docx&amp;fjbh=20200419637&amp;fjml=/fileuploadsave/CGFA/"
							 * name="开发公司定标会议纪要.docx" id="附件名" filesize=""/>
							 **/ 
							String url = nodeE.attributeValue("url"); // 附件地址
							String name = nodeE.attributeValue("name"); // 附件名称
							String filesize = nodeE.attributeValue("filesize"); // 附件大小
							recordData.add("name", "附件名称", name);
							recordData.add("url", "附件地址", url);
							recordData.add("filesize", "附件大小", filesize);
							fileInfo.add(recordData);
						}
						fileInfo.setName("附件信息");
						businessData.setFileInfo(fileInfo);
					}
					
					// 返回信息
					if (rootE.element("pecInfo").element("resultInfo") != null) {
						DictionaryCanvasData resultInfo = new DictionaryCanvasData();
						Element resultInfoElement = rootE.element("pecInfo").element("resultInfo");
						for (Iterator<Element> resultInfoIterable = resultInfoElement.elementIterator(); resultInfoIterable
								.hasNext();) {
							Element resultElement = resultInfoIterable.next();
							resultInfo.add(resultElement.attributeValue("name"), resultElement.attributeValue("value"));
						}
						resultInfo.setName("返回信息");
						businessData.setResultInfo(resultInfo);
					}
					
				}
			}
		} catch (Exception e) {
			logger.error("报错日志：类名称、PurchaseTaskServiceImpl；方法名、getDetails；报错内容、" + e.getMessage());
			return Result.error(CodeMsg.SERVER_ERROR.fillArgs(e.getMessage()));
		}
		return Result.success(businessData);
	}
	
	/**
	 * 
	 * 创建人 : yn
	 * 创建时间 : 2020年5月20日 下午2:34:02
	 * 描述 : 解析soapXml
	 * 包名 : com.chinacoal.microservice.impl.service.impl
	 * 方法名 : analysisSoapXml
	 *  String  
	 *  @throws
	 */
	public static String analysisSoapXml(String soapXml, String key) {
		try {
			Document doc = DocumentHelper.parseText(soapXml);
			Element root = doc.getRootElement(); // 获取根节点
			Element elm = root.element("Body");
			// 获取Body下的所有子节点
			List<?> bodyChild = elm.elements();
			// 遍历所有的Body当前节点
			for (Iterator<?> it = bodyChild.iterator(); it.hasNext();) {
				Element elm1 = (Element) it.next();
				List<?> responseChild = elm1.elements();
				// 遍历Response节点下的所有节点
				for (Iterator<?> it1 = responseChild.iterator(); it1.hasNext();) {
					Element elm2 = (Element) it1.next();
					// 取得最后节点下的名称和值
					if (key.equals(elm2.getName())) {
						return elm2.getText();
					}
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return null;
	}
	
	/**
	 * 
	 * 创建人 : yn
	 * 创建时间 : 2020年5月20日 下午2:49:48
	 * 描述 : “审核意见”解密
	 * 包名 : com.chinacoal.microservice.impl.service.impl
	 * 方法名 : unicode
	 *  String  
	 *  @throws
	 */
	public static String unicode(String unicodeStr) {
		int start = 0;
		int end = 0;
		final StringBuffer buffer = new StringBuffer();
		while (start > -1) {
			end = unicodeStr.indexOf("\\u", start + 2);
			String charStr = "";
			if (end == -1) {
				charStr = unicodeStr.substring(start + 2, unicodeStr.length());
			} else {
				charStr = unicodeStr.substring(start + 2, end);
			}
			char letter = (char) Integer.parseInt(charStr, 16); // 16进制parse整形字符串。
			buffer.append(new Character(letter).toString());
			start = end;
		}
		String value = buffer.toString();
		return value;
	}
	
}
